package com.spider.admin.agent.conf;

import com.spider.admin.conf.ENVConf;
import com.spider.admin.utils.CommonUtil;
import com.spider.admin.utils.FileUtils;
import com.spider.admin.utils.OSCommandUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


@Component
public class AdminWebConf {

    @Autowired
    private ENVConf envConf;

    private String getWebConf() {
        String apiServerContext = CommonUtil.getRuntimeIP();
        if (envConf.getServerPort() != null && envConf.getServerPort().intValue() != 80) {
            apiServerContext = apiServerContext + ":" + envConf.getServerPort();
        }
        if (StringUtils.isNotEmpty(envConf.getServerContextPath()) && !"/".equals(envConf.getServerContextPath())) {
            apiServerContext = apiServerContext + envConf.getServerContextPath();
        }
        String confInfo = "upstream managerApiServer {\n" +
                "    server " + apiServerContext + ";\n" +
                "}\n" +
                "server {\n" +
                "    listen       80;\n" +
                "    server_name  " + envConf.getWebDomain() + ";\n" +
                "\n" +
                "    location / {\n" +
                "        root html;\n" +
                "        index index.html index.htm;\n" +
                "    }\n" +
                "\n" +
                "    location /api/ {  \n" +
                "        access_by_lua_file hgg-lua/access_control.lua;          \n" +
                "        proxy_pass   http://managerApiServer/;\n" +
                "    }\n" +
                "    location /verify { #验证token服务\n" +
                "        internal;           #内部location，不能外部调用\n" +
                "        proxy_pass   http://managerApiServer/verify;\n" +
                "        proxy_set_header Content-type \"application/json\";\n" +
                "    }\n" +
                "}";
        return confInfo;
    }

    public void writeAdminWebConf() {
        try {
            String adminWebConfPath = null;
            if (OSCommandUtil.isWinOS()) {
                adminWebConfPath = envConf.getUiContainerBasePath() + "/spider_conf/server-admin/v1.0/server-default.conf";
            } else {
                adminWebConfPath = envConf.getUiContainerBasePath() + "/nginx/spider_conf/server-admin/v1.0/server-default.conf";
            }
            FileUtils.writeFile(adminWebConfPath, getWebConf());
        } catch (Exception e) {
            throw new RuntimeException("管理应用发布配置生成异常：" + e.getMessage());
        }
    }
}
